package com.flyduck.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.flyduck.common.exception.BusinessException;
import com.flyduck.entity.AppCartItem;
import com.flyduck.entity.AppProduct;
import com.flyduck.entity.AppSkuStock;
import com.flyduck.mapper.AppCartItemMapper;
import com.flyduck.mapper.AppProductMapper;
import com.flyduck.mapper.AppSkuStockMapper;
import com.flyduck.dto.AppCartItemDTO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * AppCartItemManager
 * </p>
 *
 * @author flyduck
 * @since 2024-06-18
 */
@Component
public class AppCartItemManager {
    @Resource
    private AppCartItemMapper appCartItemMapper;
    @Resource
    private AppProductMapper appProductMapper;
    @Resource
    private AppSkuStockMapper appSkuStockMapper;

    //获取购物车的商品/立即购买的商品
    public List<AppCartItemDTO> getCartItemList(List<Long> cartIds, Long userId, Long productId, Long skuId, Integer quantity){
        List<AppCartItemDTO> cartItemList;
        if (CollectionUtil.isNotEmpty(cartIds)) {
            //购物车购买
            cartItemList = appCartItemMapper.getCartItemList(
                    new QueryWrapper<AppCartItem>()
                            .eq("aci.user_id", userId)
                            .in("aci.id", cartIds)
                            .orderByDesc("aci.created")
            );
        }else {
            //立即购买
            AppProduct appProduct = appProductMapper.selectById(productId);
            if (appProduct == null || !appProduct.getIsOnSale()) {
                throw new BusinessException("商品未上架");
            }

            AppCartItemDTO appCartItemDTO = new AppCartItemDTO();
            appCartItemDTO.setProductId(productId);
            appCartItemDTO.setSkuId(skuId);
            appCartItemDTO.setQuantity(quantity);
            appCartItemDTO.setProductName(appProduct.getName());
            appCartItemDTO.setProductImage(appProduct.getImage());
            appCartItemDTO.setProductSn(appProduct.getSn());
            appCartItemDTO.setCategoryId(appProduct.getCategoryId());
            appCartItemDTO.setUserId(userId);

            if(skuId == -1){
                appCartItemDTO.setPrice(appProduct.getPrice());
                appCartItemDTO.setSku("默认规格");
            }else {
                AppSkuStock appSkuStock = appSkuStockMapper.selectById(skuId);
                appCartItemDTO.setPrice(appSkuStock.getPrice());
                appCartItemDTO.setSku(appSkuStock.getSku());
            }
            cartItemList = new ArrayList<>();
            cartItemList.add(appCartItemDTO);
        }
        return cartItemList;
    }
}
